package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.RedisUtils;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.RoleIdEnum;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBxdMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyBxdParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyElmsxfParam;
import cn.stylefeng.guns.sys.modular.system.model.params.ProjectParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyBxdaResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyElmsxfResult;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 档案管理表 服务实现类
 * </p>
 * @author liuy
 * @since
 */
@Service
public class BtyBxdService extends ServiceImpl<BtyBxdMapper, BtyBxd> {

    @Resource
    private UserService userService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private BtyBxdaService bxdaService;
    @Resource
    private BtyBrandService brandService;
    /**
     * 获取档案管理列表
     *
     * @author fengshuonan
     * @Date 2018/12/23 6:05 PM
     */

    public Page<Map<String, Object>> list(String condition,String status,String flag,String beginTime,String endTime,String kj,String btyBrandId,String dm,String xm,String ddName,String otherName) {
        Page page = LayuiPageFactory.defaultPage();

        return this.baseMapper.list(page, condition,status,flag,beginTime,endTime,kj,btyBrandId,dm,xm,ddName,otherName);
    }
    /**
     * 获取报销单导出excel列表(不分页)
     */
    public List<Map<String, Object>> listExport(String condition,String status,String flag,String beginTime,String endTime,String kj,String btyBrandId,String dm,String xm,String ddName,String otherName) {

        return this.baseMapper.listExport(condition,status,flag,beginTime,endTime,kj,btyBrandId,dm,xm,ddName,otherName);
    }
    public List<BtyBxda> bxrList(String kj,String dm) {
        return this.baseMapper.bxrList(kj,dm);
    }
    /**
     * 获取报销单已报销金额
     */
    public List<BtyBxd> sumZcje(String openid,String beginTime,String endTime) {
        return this.baseMapper.sumZcje(openid,beginTime,endTime);
    }
    /**
     * 获取报销单未报销金额
     */
    public List<BtyBxd> sumWbxje(String openid,String beginTime,String endTime) {
        return this.baseMapper.sumWbxje(openid,beginTime,endTime);
    }
    /**
     * 获取报销单总金额
     */
    public List<BtyBxd> sumJe(String openid,String beginTime,String endTime) {
        return this.baseMapper.sumJe(openid,beginTime,endTime);
    }
    public List<BtyBxda> bxrLists(String kj,String dm) {
        return this.baseMapper.bxrLists(kj,dm);
    }
    public List<BtyBxda> kjList(String kj) {
        return this.baseMapper.kjList(kj);
    }

   public BtyBxd info(String id){
        return this.baseMapper.info(id);
   }
    public String yaoMa(String dm){
        return this.baseMapper.yaoMa(dm);
    }
    public List<BtyBxd> dmList(String kj,String ddName) {
        return this.baseMapper.dmList(kj,ddName);
    }

    public List<BtyBxd> zcDmList(String kj) {
        return this.baseMapper.zcDmList(kj);
    }
    public List<BtyBxdaResult>zyList(){
        return baseMapper.zyList();
    }

    public Page<Map<String, Object>> listKY(String pro,String kyDate,String kyFlag,String year,String month,String day) {

        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        List<Long> roleList = currentUser.getRoleList();
        User curtuser = userService.getById(currentUser.getId());
        String phone = curtuser.getPhone();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();//开发人员
        Long role_yyjl = RoleIdEnum.ROLE_YYJL.getCode();//营运经理
        Long role_dd = RoleIdEnum.ROLE_DD.getCode();//督导
        Long role_netshop = RoleIdEnum.ROLE_NETSHOP.getCode();//网上建店负责人
        Long role_gcb = RoleIdEnum.ROLE_GCB.getCode();//工程部

        Page page = LayuiPageFactory.defaultPage();

        //开发人员
        Long createUser = null;
        if (roleList.contains(role_kfry)) {
            createUser = currentUser.getId();
        }
        //营运经理

        String yyjl = null;
        if (roleList.contains(role_yyjl)) {
            yyjl = phone;
        }
        //督导
        String dd = null;
        if (roleList.contains(role_dd)) {
            dd = phone;
        }



        return this.baseMapper.listKY(page,pro,createUser,yyjl,dd,kyFlag,kyDate,year,month,day);
    }

    public Page<Map<String, Object>> listZJ(ProjectParam projectParam) {
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        List<Long> roleList = currentUser.getRoleList();
        User curtuser = userService.getById(currentUser.getId());
        String phone = curtuser.getPhone();
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();//开发人员
        Long role_yyjl = RoleIdEnum.ROLE_YYJL.getCode();//营运经理
        Long role_dd = RoleIdEnum.ROLE_DD.getCode();//督导

        Page page = LayuiPageFactory.defaultPage();

        //开发人员
        if (roleList.contains(role_kfry)) {
            projectParam.setCreateUser(currentUser.getId());

        }
        //营运经理
        if (roleList.contains(role_yyjl)) {
            projectParam.setYyjl(phone);
        }
        //督导
        if (roleList.contains(role_dd)) {
            projectParam.setDd(phone);
        }



        return this.baseMapper.listZJ(page,projectParam);
    }

    public Page<Map<String, Object>> listZc(BtyBxdParam bxdParam) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.listZc(page,bxdParam);
    }
    public List<Map<String, Object>> listZcExport(BtyBxdParam bxdParam){
        Page page = LayuiPageFactory.defaultPage();
        return  baseMapper.listZcExport(page,bxdParam);
    }
    public String genbh(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String danhao = sdf.format(new Date());
        Long xlh = redisUtils.incr("ZC"+danhao);
        String id = "ZC"+danhao+String.format("%03d", xlh);
        return id;
    }



    public Page<Map<String, Object>> bxdList(String status, String flag, String beginTime, String endTime, String dm, String xm, List<String> roleList) {
        Page page = LayuiPageFactory.defaultPage();

        return this.baseMapper.bxdList(page, status, flag, beginTime, endTime, dm, xm, roleList);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean batchImport(String fileName, MultipartFile file) {
        boolean notNull = false;
        try {
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //System.out.println("sheets:"+sheets);
            for (int i = 0; i < 1; i++) {
                //Sheet sheet = wb.getSheetAt(i);
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    notNull = true;
                }

                int lastRowNum = sheet.getLastRowNum();
                for (int r = 1; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //获取单元格
                    for(int m=1;m<7;m++){
                        Cell cell = row.getCell(m);
                        if (ToolUtil.isNotEmpty(cell)) {
                            cell.setCellType(CellType.STRING);
                        }
                    }
                    //店名
                    String dm=row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
                    //供货商
                    String ghs = row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();
                    //支出金额
                    String zcje = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
                    //报销人
                    String bxr = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();
                    //卡号
                    String yhk = row.getCell(4) == null ?"" : row.getCell(4).getStringCellValue().replaceAll("\\s*", "");
                    //摘要
                    String zy=row.getCell(5) == null ? "" : row.getCell(5).getStringCellValue();
                    List<BtyBxda> list=bxdaService.list(new QueryWrapper<BtyBxda>().eq("yhk",yhk).eq("xm",bxr).eq("dm",dm));
                    if(list.size()<=0){
                        BtyBxda   btyBxda=new BtyBxda();
                        btyBxda.setId(UUIDUtils.getId());
                        //店名
                        btyBxda.setDm(dm);
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String bh = df.format(new Date());
                        //通过银行卡号获取银行简称
                        RestTemplate restTemplate = new RestTemplate();
                        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
                        String content = restTemplate.getForObject(url, String.class);
                        JSONObject jsonObject = JSONObject.parseObject(content);
                        String bank;
                        if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                            bank = jsonObject.get("bank").toString();
                            btyBxda.setBank(bank);
                            //通过银行简称获取行号
                            String code = bxdaService.getBankCode(bank);
                            if (ToolUtil.isNotEmpty(code) && ToolUtil.isEmpty(btyBxda.getBz())) {
                                btyBxda.setBz(code);
                            }
                        }
                        //银行卡号
                        btyBxda.setYhk(yhk);
                        btyBxda.setBh(bh);
                        //供货商
                        btyBxda.setGhs(ghs);
                        //报销人姓名
                        btyBxda.setXm(bxr);
                        //通过店名查询会计
                        BtyBrand brand=brandService.getOne(new QueryWrapper<BtyBrand>().eq("dm",dm));
                        if(ToolUtil.isNotEmpty(brand)){
                            btyBxda.setKj(brand.getCwry());
                        }
                        btyBxda.setCreateUser(LoginContextHolder.getContext().getUserId());
                        btyBxda.setCreateTime(new Date());
                        this.bxdaService.save(btyBxda);

                        BtyBxd btyBxd = new BtyBxd();
                        //通过店名查询妖码
                        String yaoMa = baseMapper.yaoMa(dm) == null ? "" : baseMapper.yaoMa(dm);
                        btyBxd.setBtyBxdaId(btyBxda.getId().toString());
                        btyBxd.setId(UUIDUtils.getId());
                        btyBxd.setBh(bh);
                        //妖码
                        btyBxd.setYaoMa(yaoMa);
                        //店名
                        btyBxd.setDm(dm);
                        //摘要
                        btyBxd.setZy(zy);
                        //支出金额
                        btyBxd.setZcje(zcje);
                        btyBxd.setCreateUser(LoginContextHolder.getContext().getUserId());
                        btyBxd.setCreateTime(new Date());
                        this.baseMapper.insert(btyBxd);
                    }
                    else{
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String bh = df.format(new Date());
                        BtyBxd btyBxd = new BtyBxd();
                        //通过店名查询妖码
                        String yaoMa = baseMapper.yaoMa(dm) == null ? "" : baseMapper.yaoMa(dm);
                        btyBxd.setBtyBxdaId(list.get(0).getId().toString());
                        btyBxd.setId(UUIDUtils.getId());
                        btyBxd.setBh(bh);
                        //妖码
                        btyBxd.setYaoMa(yaoMa);
                        //店名
                        btyBxd.setDm(dm);
                        //摘要
                        btyBxd.setZy(zy);
                        //支出金额
                        btyBxd.setZcje(zcje);
                        btyBxd.setCreateUser(LoginContextHolder.getContext().getUserId());
                        btyBxd.setCreateTime(new Date());
                        this.baseMapper.insert(btyBxd);
                    }
                }
            }
        } catch (Exception e) {
            notNull=false;
            e.printStackTrace();
        }
        return notNull;
    }
}
